<?php
// proxy_simple.php - 简化版代理（使用stream_context）
session_start();

$url = $_GET['url'] ?? '';
$type = $_GET['type'] ?? 'download';
$filename = $_GET['filename'] ?? 'download';

if (empty($url)) {
    http_response_code(400);
    exit('缺少URL参数');
}

// 解码URL
$url = urldecode($url);

if (!filter_var($url, FILTER_VALIDATE_URL)) {
    http_response_code(400);
    exit('无效的URL');
}

// 根据资源URL自动设置对应的Referer和UA
function getHeadersByUrl($url) {
    $host = parse_url($url, PHP_URL_HOST);
    $headers = [
        'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
        'Accept: */*',
        'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8',
        'Connection: close'
    ];
    
    // 设置Referer
    if (strpos($host, 'douyin') !== false) {
        $headers[] = 'Referer: https://www.douyin.com/';
    } elseif (strpos($host, 'xiaohongshu') !== false || strpos($host, 'xhscdn') !== false) {
        $headers[] = 'Referer: https://www.xiaohongshu.com/';
    } elseif (strpos($host, 'kuaishou') !== false) {
        $headers[] = 'Referer: https://www.kuaishou.com/';
    } elseif (strpos($host, 'pipix') !== false) {
        $headers[] = 'Referer: https://www.pipix.com/';
    } else {
        $headers[] = 'Referer: https://' . $host . '/';
    }
    
    return $headers;
}

set_time_limit(300);

// 设置内容类型
if ($type === 'image') {
    header('Content-Type: image/jpeg');
} elseif ($type === 'video') {
    header('Content-Type: video/mp4');
} else {
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
}

// 使用file_get_contents with stream context
$context = stream_context_create([
    'http' => [
        'method' => 'GET',
        'header' => implode("\r\n", getHeadersByUrl($url)),
        'timeout' => 300,
        'ignore_errors' => true // 忽略HTTP错误码，继续获取内容
    ],
    'ssl' => [
        'verify_peer' => false,
        'verify_peer_name' => false
    ]
]);

try {
    $content = file_get_contents($url, false, $context);
    if ($content === false) {
        throw new Exception('无法获取内容');
    }
    echo $content;
} catch (Exception $e) {
    http_response_code(500);
    echo '代理错误: ' . $e->getMessage();
}
?>